//
//  ViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/1/16.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "ViewController.h"
#import "InsuranceBrokersViewController.h"
#import "NewsViewController.h"
#import "UserSetViewController.h"
#import "ProductKeysView.h"

@interface ViewController ()<UIScrollViewDelegate,UITextFieldDelegate,ProductKeysViewDelegate>{
    UIScrollView *scrollBG;
    UITextField *txtSarch;
    
    NSArray *arrayBtns;
    NSArray *arraycate;
    NSDictionary *dicData;
    
    UILabel *lblNavTitle;
    UIView *viewButtonBG;
    
    ProductKeysView *productKey;
    
}

@end

@implementation ViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    txtSarch.text=@"";
    if (dicData) {
        [self refreshRed];
    }
    //注册监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    NSLog(@"---->动态键盘高度:%f",distanceToMove);
    if (!productKey) {
        productKey=[[ProductKeysView alloc] init];
        [self.view addSubview:productKey];
        productKey.delegate=self;
    }
    productKey.frame=CGRectMake(0, Y(scrollBG), kScreenWidth, kScreenHeight-distanceToMove-Y(scrollBG));
    [productKey showAllArray:[[Utility Share] arrayProductKeys]];
    
    [UIView animateWithDuration:0.3 animations:^{
       
    } completion:^(BOOL finished) {
        
    }];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    [productKey hidden];
    [UIView animateWithDuration:0.3 animations:^{
        
    }completion:^(BOOL finished) {
        
    }];
}//
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.44
    
    RegisterNotify(@"againLoadUserData", @selector(againLoadUserData))
    
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
    [self.view addGestureRecognizer:tap];
    
    [self.view addSubview:[RHMethods imageviewWithFrame:CGRectMake(0, 0, kScreenWidth, 108) defaultimage:@"TapNavBig070116"]];
    lblNavTitle=[RHMethods labelWithFrame:CGRectMake(0, 20, kScreenWidth, 44) font:BoldFont(19) color:[UIColor whiteColor] text:@"牌照大厅" textAlignment:NSTextAlignmentCenter];
    [self.view addSubview:lblNavTitle];
    UIButton *btnRight=[RHMethods buttonWithFrame:CGRectMake(kScreenWidth-60, 20, 60, 44) title:nil image:@"headSet070116" bgimage:nil];
    [btnRight setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    [btnRight setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btnRight addTarget:self action:@selector(rightButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnRight];
    
    UIView *viewTxtBG=[[UIView alloc] initWithFrame:CGRectMake(10, 68, kScreenWidth-20, 30)];
    viewTxtBG.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:viewTxtBG];
    [[Utility Share] viewLayerRound:viewTxtBG borderWidth:1 borderColor:[UIColor clearColor]];
    
    txtSarch=[RHMethods textFieldlWithFrame:CGRectMake(10, 0, W(viewTxtBG)-10, 30) font:fontTitle color:rgbTitleColor placeholder:@"" text:@""];
    [viewTxtBG addSubview:txtSarch];
    [txtSarch setLeftView:[RHMethods imageviewWithFrame:CGRectMake(0, 0, 26, 30) defaultimage:@"searchIcon070116" contentMode:UIViewContentModeCenter] ];
    [txtSarch setLeftViewMode:UITextFieldViewModeAlways];
    [txtSarch setReturnKeyType:UIReturnKeySearch];
    txtSarch.delegate=self;
    
    scrollBG=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 108, kScreenWidth, H(self.view)-188)];
    scrollBG.backgroundColor=rgbGray;
    scrollBG.delegate=self;
    [self.view addSubview:scrollBG];
    scrollBG.autoresizingMask=UIViewAutoresizingFlexibleHeight;
    
    viewButtonBG=[[UIView alloc] initWithFrame:CGRectMake(0, YH(scrollBG), kScreenWidth, 80)];
    [viewButtonBG setBackgroundColor:[UIColor whiteColor]];
    viewButtonBG.autoresizingMask=UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:viewButtonBG];
//    //
//    float fw_btn=70;
//    float fw_t=(kScreenWidth-fw_btn*3)/4.0;
//    float fx=fw_t;
//    for (int i=0; i<3; i++) {
//        NSString *strImageName=[NSString stringWithFormat:@"zixun0%d070116",i+1];//@"zixun01070116"
//        UIButton *btn01=[RHMethods buttonWithFrame:CGRectMake(fx, 0, fw_btn,80) title:nil image:strImageName bgimage:nil];
//        [btn01 addTarget:self action:@selector(bottomButtonClicekd:) forControlEvents:UIControlEventTouchUpInside];
//        btn01.tag=100+i;
//        [viewButtonBG addSubview:btn01];
//        fx+=(fw_t+fw_btn);
//    }
    
    
    
    
    if ([[[Utility Share] userId] notEmptyOrNull] && [[[Utility Share] userToken] notEmptyOrNull]) {
        [[Utility Share] isLogin:^(NSInteger NoLogin) {
            if (NoLogin != 1) {
                [[Utility Share] showLoginAlert:YES];
            }else{
                [[Utility Share] versionUpdate:NO];
                [self againLoadUserData];
            }
        }];
    }else{
        [[Utility Share] showLoginAlert:NO];
    }
    
}
-(void)refreshRed{
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:XHFwelcomehome,[[Utility Share] userId],[[Utility Share] userToken]] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
           NSArray * arrayT=[[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"];
            for (NSDictionary *dic in arrayT) {
                UIView *viewT=[scrollBG viewWithTag:10000+[[dic valueForJSONStrKey:@"id"] integerValue]];
                if (viewT) {
                    viewT.hidden=[[dic valueForJSONStrKey:@"newanswer"] integerValue]<=0;
                }
                
            }
         
        }
    } onError:^(NSError *error) {
       
    }];
}
#pragma mark selector
-(void)againLoadUserData{
    [[Utility Share] hiddenStartTransitionView];
//XHFwelcomehome
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:XHFwelcomehome,[[Utility Share] userId],[[Utility Share] userToken]] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            dicData=[resData objectForJSONKey:@"data"];
            [[Utility Share] setArrayLevel:[[resData objectForJSONKey:@"data"] objectForJSONKey:@"level"]];
            arrayBtns=[[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"];
            arraycate=[[resData objectForJSONKey:@"data"] objectForJSONKey:@"cate"];
            NSString *strTitle=[NSString stringWithFormat:@"牌照大厅(%@)",[dicData valueForJSONStrKey:@"allproductsnum"]];
            lblNavTitle.text=strTitle;
            
            float fw=[dicData valueForJSONStrKey:@"allproductsnum"].length+2;
            NSMutableAttributedString *strC = [[NSMutableAttributedString alloc] initWithString:strTitle];
            [strC addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:NSMakeRange(strTitle.length-fw, fw)];
//            [strC addAttribute:NSForegroundColorAttributeName value:RGBCOLOR(247, 177, 66) range:NSMakeRange(0, @"900".length)];
            lblNavTitle.attributedText = strC;
            [self refreshScrollView];
        }else{
            [self againLoadUserData];
        }
    } onError:^(NSError *error) {
        [self againLoadUserData];
    }];
    [self loadProductskeywords];
}
-(void)loadProductskeywords{
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:XKFproductskeywords,[[Utility Share] userId],[[Utility Share] userToken],@""] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            [[Utility Share] setArrayProductKeys:[[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"]];
        }else{
            [self loadProductskeywords];
        }
    } onError:^(NSError *error) {
        [self loadProductskeywords];
    }];
}

-(void)refreshScrollView{
    for (UIView *vt in [scrollBG subviews]) {
        [vt removeFromSuperview];
    }
    
    float fw_jg=10;
    float fw_btn=(kScreenWidth- fw_jg*4)/3.0;
    float fx=fw_jg;
    float fy=fw_jg;
    for (int i=0; i<[arrayBtns count]; i++) {
        if (i%3==0) {
            fx=fw_jg;
            if (i!=0) {
                fy+=fw_jg+fw_btn;
            }
        }
        NSDictionary *dic=[arrayBtns objectAtIndex:i];
        UIImageView *imageViewBG=[RHMethods imageviewWithFrame:CGRectMake(fx, fy, fw_btn, fw_btn) defaultimage:@"pzflbg070116" contentMode:UIViewContentModeScaleAspectFit];
        [scrollBG addSubview:imageViewBG];
        
        UILabel *lblTitle=[RHMethods labelWithFrame:CGRectMake(fx+10, fy+fw_btn/2-15, fw_btn-20, 0) font:[UIFont fontWithName:@"Verdana-Bold" size:16] color:RGBCOLOR(178, 37, 39) text:[[dic valueForJSONStrKey:@"name"] stringByReplacingOccurrencesOfString:@"|" withString:@"\n"] textAlignment:NSTextAlignmentCenter];
        [scrollBG addSubview:lblTitle];
        if (H(lblTitle)>20) {
            lblTitle.frameHeight=40;
            lblTitle.frameY=fy+fw_btn/2-25;
        }
        
        UILabel *lblS=[RHMethods labelWithFrame:CGRectMake(X(lblTitle), YH(lblTitle), W(lblTitle), 20) font:Font(16) color:RGBCOLOR(178, 37, 39) text:[NSString stringWithFormat:@"(%@)",[dic valueForJSONStrKey:@"numbers"]] textAlignment:NSTextAlignmentCenter];
        [scrollBG addSubview:lblS];
        if (H(lblTitle)>20) {
            lblS.frameY=YH(lblTitle)-3;
        }
        
        UIButton *btnTemp=[RHMethods buttonWithFrame:imageViewBG.frame title:@"" image:nil bgimage:nil];
        [btnTemp addTarget:self action:@selector(typeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        btnTemp.tag=10+i;
        [scrollBG addSubview:btnTemp];
        fx+=fw_jg+fw_btn;
        
        //02-04
//        红点添加
        UIImageView *imageV=[RHMethods imageviewWithFrame:CGRectMake(XW(btnTemp)-15*kScreenWidth/320.0,Y(btnTemp)+ kScreenWidth/320.0, 7, 14) defaultimage:@"redTip070116" contentMode:UIViewContentModeCenter];
        imageV.tag=10000+[[dic valueForJSONStrKey:@"id"] integerValue];
        [scrollBG addSubview:imageV];
        imageV.hidden=[[dic valueForJSONStrKey:@"newanswer"] integerValue]<=0;
    }
    float contetH= fy+2*fw_jg+fw_btn;
    
    if ([[dicData valueForJSONStrKey:@"notice"] notEmptyOrNull]) {
        UIView *viewTemp=[[UIView alloc] initWithFrame:CGRectMake(fw_jg, contetH, W(scrollBG)-2*fw_jg, 20)];
        viewTemp.backgroundColor=[UIColor whiteColor];
        viewTemp.layer.masksToBounds = YES;
        viewTemp.layer.cornerRadius =10.0;
        viewTemp.layer.borderWidth=1;
        viewTemp.layer.borderColor =[[UIColor whiteColor] CGColor];
        [scrollBG addSubview:viewTemp];
        
        [viewTemp addSubview:[RHMethods imageviewWithFrame:CGRectMake(0, 0, 30, 44) defaultimage:@"laba" contentMode:UIViewContentModeCenter]];
        [viewTemp addSubview:[RHMethods labelWithFrame:CGRectMake(25, 10, 0, 20) font:BoldFont(15) color:rgbTitleColor text:@"公告："]];
        UILabel *lblContent=[RHMethods labelWithFrame:CGRectMake(25, 35, W(viewTemp)-35, 0) font:Font(14) color:rgbTxtDeepGray text:[dicData valueForJSONStrKey:@"notice"] textAlignment:NSTextAlignmentLeft setLineSpacing:4];
        [viewTemp addSubview:lblContent];
        viewTemp.frameHeight=YH(lblContent)+10;
        contetH=YH(viewTemp)+10;
    }
    [scrollBG setContentSize:CGSizeMake(0,contetH )];
    
    //
    NSInteger count1=arraycate.count;
    count1=count1<=3?count1:3;
    float fw_btn2=70;
    float fw_t2=(kScreenWidth-fw_btn2*count1)/(count1+1);
    float fx2=fw_t2;
    ///
    for (UIView *vt in [viewButtonBG subviews]) {
        [vt removeFromSuperview];
    }
    
    for (int i=0; i<count1; i++) {
        UIImageView *imageV=[RHMethods imageviewWithFrame:CGRectMake(fx2, 5, fw_btn2,70) defaultimage:@"" contentMode:UIViewContentModeScaleAspectFit];
        [viewButtonBG addSubview:imageV];
        [imageV imageWithURL:[[arraycate objectAtIndex:i] valueForJSONStrKey:@"2x_path"] useProgress:NO useActivity:NO];
        UIButton *btn01=[RHMethods buttonWithFrame:CGRectMake(fx2, 0, fw_btn2,80) title:nil image:@"" bgimage:nil];
        [btn01 addTarget:self action:@selector(bottomButtonClicekd:) forControlEvents:UIControlEventTouchUpInside];
        btn01.tag=100+i;
        [viewButtonBG addSubview:btn01];
        fx2+=(fw_t2+fw_btn2);
    }
    
}

#pragma mark button
-(void)rightButtonClicked{
    [self hiddenKeyBoard];
    [self pushController:[UserSetViewController class] withInfo:@"" withTitle:@" " withOther:nil];
}
-(void)bottomButtonClicekd:(UIButton *)btn{
    NSString *strTitle=@"";
    //[{"id":"1","name":"莘学校"},{"id":"2","name":"莘开拓"},{"id":"3","name":"莘快讯"}]}}
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:[arraycate objectAtIndex:btn.tag-100]];
//    if (btn.tag==100) {
//        //莘学校
//        strTitle=[dic valueForJSONStrKey:@"name"];
//        [dic setValue:[dic valueForJSONStrKey:@"name"] forKey:@"subTitle"];
////        dic=@{@"id":@"1",@"subTitle":@"学校详情"};
//    }else if (btn.tag==101) {
//        //莘开拓
//        strTitle=@"莘开拓";
//        dic=@{@"id":@"2",@"subTitle":@"开拓详情"};
//    }else if (btn.tag==102) {
//        //莘快讯
//        strTitle=@"莘快讯";
//        dic=@{@"id":@"3",@"subTitle":@"快讯详情"};
//    }
    strTitle=[dic valueForJSONStrKey:@"name"];
    [dic setValue:[dic valueForJSONStrKey:@"name"] forKey:@"subTitle"];
    [self pushController:[NewsViewController class] withInfo:@"" withTitle:strTitle withOther:dic];
}
-(void)hiddenKeyBoard{
    [txtSarch resignFirstResponder];
}

-(void)typeButtonClicked:(UIButton *)btn{
    [self hiddenKeyBoard];
    NSDictionary *dic=[arrayBtns objectAtIndex:btn.tag-10];
    [self pushController:[InsuranceBrokersViewController class] withInfo:@"" withTitle:[[dic valueForJSONStrKey:@"name"] stringByReplacingOccurrencesOfString:@"|" withString:@" "] withOther:dic];
//    DLog(@"点击%d",btn.tag);
}
#pragma mark UIScrollViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self hiddenKeyBoard];
    DLog(@"滚动");
}
#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self pushController:[InsuranceBrokersViewController class] withInfo:@"search" withTitle:@"牌照大厅" withOther:@{@"txt":textField.text}];
    [textField resignFirstResponder];
    return YES;
}
#pragma mark ProductKeysViewDelegate
-(void)productKeysView:(ProductKeysView *)selectView clickeDic:(NSDictionary *)dic{
    [txtSarch resignFirstResponder];
      [self pushController:[InsuranceBrokersViewController class] withInfo:@"search" withTitle:@"牌照大厅" withOther:dic];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
